package com.example.myapplication.customizeView.watchFace;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.example.myapplication.R;
import com.example.myapplication.customizeView.utils.SizeUtils;

import java.util.Calendar;
import java.util.TimeZone;

public class WatchFaceView extends View {

    private static final String TAG = "WatchFaceView";
    private int mSecondColor;
    private int mMinuteColor;
    private int mHourColor;
    private int mScaleColor;
    private int mResBgId;
    private boolean mIsScaleShow;
    private Paint mSecondPaint;
    private Paint mMinutePaint;
    private Paint mHourPaint;
    private Paint mScalePaint;
    private Bitmap mBackgroundImage = null;
    private int mWidth;
    private int mHeight;
    private Rect mSrcRect;
    private Rect mDesRect;
    private Calendar mCalendar;
    private int mInnerCircleRadius = SizeUtils.dip2px(getContext(),3);
    private boolean isUpdate = false;

    public WatchFaceView(Context context) {
        this(context,null);
    }

    public WatchFaceView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public WatchFaceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //获取属性
        initAttrs(context, attrs);
        //拿到日历实例
        mCalendar = Calendar.getInstance();
        //设置时区
        mCalendar.setTimeZone(TimeZone.getDefault());
        //创建画笔
        initPaints();

    }



    /**
     * 创建相关画笔
     */
    private void initPaints() {
        //秒针画笔
        mSecondPaint = new Paint();
        mSecondPaint.setColor(mSecondColor);
        mSecondPaint.setStyle(Paint.Style.STROKE);
        mSecondPaint.setStrokeWidth(2f);
        mSecondPaint.setAntiAlias(true);
        //分针画笔
        mMinutePaint = new Paint();
        mMinutePaint.setColor(mMinuteColor);
        mMinutePaint.setStyle(Paint.Style.STROKE);
        mMinutePaint.setStrokeWidth(3f);
        mMinutePaint.setAntiAlias(true);
        //时针画笔
        mHourPaint = new Paint();
        mHourPaint.setColor(mHourColor);
        mHourPaint.setStyle(Paint.Style.STROKE);
        mHourPaint.setStrokeWidth(15f);
        mHourPaint.setAntiAlias(true);
        //刻度画笔
        mScalePaint = new Paint();
        mScalePaint.setColor(mScaleColor);
        mScalePaint.setStyle(Paint.Style.STROKE);
        mScalePaint.setStrokeWidth(5f);
        mScalePaint.setAntiAlias(true);

    }

    private void initAttrs(Context context, @Nullable AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.WatchFace);
        mSecondColor = a.getColor(R.styleable.WatchFace_secondColor, getResources().getColor(R.color.secondDefaultColor));
        mMinuteColor = a.getColor(R.styleable.WatchFace_minuteColor, getResources().getColor(R.color.minuteDefaultColor));
        mHourColor = a.getColor(R.styleable.WatchFace_hourColor, getResources().getColor(R.color.hourDefaultColor));
        mScaleColor = a.getColor(R.styleable.WatchFace_scaleColor, getResources().getColor(R.color.scaleDefaultColor));
        mResBgId = a.getResourceId(R.styleable.WatchFace_faceBg, -1);
        mIsScaleShow = a.getBoolean(R.styleable.WatchFace_scaleShow, true);

        if(mResBgId!=-1){
            mBackgroundImage = BitmapFactory.decodeResource(getResources(), mResBgId);
        }
        a.recycle();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        isUpdate = true;
        post(new Runnable() {
            @Override
            public void run() {
                if (isUpdate){
                    invalidate();
                    postDelayed(this,1000);

                }else {
                    removeCallbacks(this);

                }
            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        this.isUpdate=false;

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //测量自己
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        //减去内边距
        int widthTargetSize = widthSize-getPaddingLeft()-getPaddingRight();
        int heightTargetSize = heightSize-getPaddingTop()-getPaddingBottom();
        //判断大小，去小的那个
        int targetSize = Math.min(widthTargetSize,heightTargetSize);
        setMeasuredDimension(targetSize,targetSize);

        //初始化Rect
        initRect();
    }

    private void initRect() {
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
        if (mBackgroundImage==null){
            Log.d(TAG, "你没背景图。。");
            return;
        }
        //原坑
        mSrcRect = new Rect();
        mSrcRect.left=0;
        mSrcRect.top=0;
        mSrcRect.right=mBackgroundImage.getWidth();
        mSrcRect.bottom=mBackgroundImage.getHeight();
        //目标坑
        mDesRect = new Rect();
        mDesRect.left=0;
        mDesRect.top=0;
        mDesRect.right=mWidth;
        mDesRect.bottom=mHeight;


    }

    @Override
    protected void onDraw(Canvas canvas) {
        //设置时间
        long currentTimeMillis = System.currentTimeMillis();
        mCalendar.setTimeInMillis(currentTimeMillis);
        //绘制背景
        canvas.drawColor(Color.parseColor("#000000"));
        //绘制刻度和中心点
        drawScale(canvas);
        //绘制指针：时针，分针，秒针
        int radius = (int) (mWidth/2f);
        /**
         * 时针
         */
        DrawHourLine(canvas, radius);
        /**
         * 分针
         */

        DrawMinuteLine(canvas, radius);
        /**
         * 秒针
         */
        DrawSecondLine(canvas, radius);
    }

    private void DrawSecondLine(Canvas canvas, int radius) {
        int secondValue = mCalendar.get(Calendar.SECOND);
        int secondRadius = (int) (radius*0.8f);//秒针长度
        float secondRotate = secondValue * 6f ;
        canvas.save();
        canvas.rotate(secondRotate,radius,radius);
        canvas.drawLine(radius,radius-secondRadius,radius,radius-mInnerCircleRadius,mSecondPaint);
        canvas.restore();
    }

    private void DrawMinuteLine(Canvas canvas, int radius) {
        int minuteValue = mCalendar.get(Calendar.MINUTE);
        int minuteRadius = (int) (radius*0.7f);//分针长度
        float minuteRotate = minuteValue * 6f;
        canvas.save();
        canvas.rotate(minuteRotate,radius,radius);
        canvas.drawLine(radius,radius-minuteRadius,radius,radius-mInnerCircleRadius,mMinutePaint);
        canvas.restore();
    }

    private void DrawHourLine(Canvas canvas, int radius) {
        int hourRadius = (int) (radius *0.6f);//时针长度
        int hourValue = mCalendar.get(Calendar.HOUR);
        float hourOffsetRotate = mCalendar.get(Calendar.MINUTE)*0.5f;
        float hourRotate = hourValue*30+hourOffsetRotate;
        canvas.save();
        canvas.rotate(hourRotate, radius, radius);
        canvas.drawLine(radius, radius -hourRadius, radius, radius - mInnerCircleRadius,mHourPaint);
        canvas.restore();
    }

    private void drawScale(Canvas canvas) {
        //mBackgroundImage = null ;
        if (mBackgroundImage!=null){
            canvas.drawBitmap(mBackgroundImage,mSrcRect,mDesRect,mScalePaint);
        }else{
            int radius = (int) (mWidth/2f);
            //内环半径
            int innerC = (int) (mWidth/2 * 0.85f);
            //外环半径
            int outerC = (int) (mWidth/2 * 0.95f);
            /**

             绘制刻度方法1：坐标系发
             *
             */
            //for (int i = 0; i < 12; i++) {
            //    //对应角度大小
            //    double th = i*Math.PI*2/12;
            //    //内环
            //    int innerB = (int) (Math.cos(th)*innerC);
            //    int innerY = mHeight/2 - innerB;
            //    int innerA = (int) (Math.sin(th)*innerC);
            //    int innerX = mWidth/2+innerA;
            //    //外环
            //    int outerB = (int) (Math.cos(th)*outerC);
            //    int outerY = mHeight/2 - outerB;
            //    int outerA = (int) (Math.sin(th)*outerC);
            //    int outerX = mWidth/2+outerA;
//
            //    canvas.drawLine(innerX,innerY,outerX,outerY,mScalePaint);
            //}

            /**
             * 绘制刻度方法2:旋转
             */

            canvas.save();
            for (int i = 0; i < 12; i++) {
                canvas.drawLine(radius,radius-outerC,radius,radius-innerC,mScalePaint);
                canvas.rotate(30,radius,radius);
            }
            canvas.restore();

            /**
             * 绘制中心点
             */
            canvas.drawCircle(radius,radius, SizeUtils.dip2px(getContext(),mInnerCircleRadius),mScalePaint);

        }
    }
}
